package cn.edu.sjtu.gateway.filter;

import cn.edu.sjtu.gateway.model.RespStatus;
import cn.edu.sjtu.gateway.util.JWTUtil;
import cn.edu.sjtu.gateway.util.ResultUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
public class AuthorizationGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthorizationGatewayFilterFactory.Config> {

    public AuthorizationGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
            Integer role = JWTUtil.decodeRole(token);
            if (config.getRoles().stream().noneMatch(role::equals)) {
                return ResultUtil.writeError(exchange, RespStatus.NON_AUTHORITY);
            }
            return chain.filter(exchange);
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("roles");
    }

    public static class Config {

        private List<Integer> roles;

        public Config() {}

        public List<Integer> getRoles() {
            return roles;
        }

        public void setRoles(List<Integer> roles) {
            this.roles = roles;
        }
    }
}
